package com.example.xml2word;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import freemarker.template.Version;

import java.io.*;
import java.net.URL;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;

/**
 * @author jiyupeng
 * 生成doc格式的word文档
 * 这里导出的doc格式的word文档，只是直接将wordxml后缀名改为doc。
 * 所以如果在手机中使用wps打开会出现xml文档，无法解析为word的情况。
 */
public class XmlToDoc {

    public static void main(String[] args) throws IOException, TemplateException {
        Configuration configuration = new Configuration(Configuration.getVersion());
        configuration.setDefaultEncoding("UTF-8");

        URL resource = XmlToDoc.class.getClassLoader().getResource("");
        if(resource != null){
            File resourceDir = new File(resource.getFile());
            configuration.setDirectoryForTemplateLoading(resourceDir);
            Template template = configuration.getTemplate("docTemplate.ftl");

            File docFile = new File(resource.getFile() + "out/导出.doc");
            File docDir = docFile.getParentFile();
            if(!docDir.exists()) {
                docDir.mkdirs();
            }
            FileOutputStream docFileOut = new FileOutputStream(docFile);
            BufferedWriter docWriter = new BufferedWriter(new OutputStreamWriter(docFileOut));
            Map<String, Object> dataMap = new HashMap<>();
            dataMap.put("title", "标题");
            dataMap.put("persons", DataGenerate.getData());
            template.process(dataMap, docWriter);
            docWriter.flush();
            docWriter.close();
        }
    }
}
